﻿using Microsoft.Practices.Unity;
using System.Web.Mvc;
﻿using System;
using System.Collections.Generic;
using System.Web.Http.Controllers;

namespace Deixei.Infrastructure
{
    public class UnityDependencyResolver : IDependencyResolver
    {
        protected IDependencyResolver Resolver
        {
            get;
            private set;
        }

        protected IUnityContainer Container
        {
            get;
            private set;
        }

        public UnityDependencyResolver(IUnityContainer container, IDependencyResolver resolver)
        {
            Container = container;
            Resolver = resolver;
        }

        public object GetService(Type serviceType)
        {
            if (typeof(IHttpController).IsAssignableFrom(serviceType))
            {
                return this.Container.Resolve(serviceType);
            }

            try
            {
                return this.Container.Resolve(serviceType);
            }
            catch
            {
                return this.Resolver.GetService(serviceType);
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return this.Container.ResolveAll(serviceType);
            }
            catch
            {
                return this.Resolver.GetServices(serviceType);
            }
            
        }

        public void Dispose()
        {
            Container.Dispose();
        }

    }  
}
